package com.cqc.okokhttpdemo02;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.cqc.okokhttpdemo02.base.BaseActivity;
import com.cqc.okokhttpdemo02.event.AppEvent;
import com.cqc.okokhttpdemo02.event.HttpErrorEvent;
import com.cqc.okokhttpdemo02.event.HttpSuccessEvent;
import com.cqc.okokhttpdemo02.http.RequestTag;
import com.cqc.okokhttpdemo02.http.UserRequest;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * btn1 + btn2 + btn3 + btn4练习使用OkHttp
 * btn5 + btn6 + btn7 + btn8对OkHttp进行了封装，并使用了EventBus传递值
 */
public class MainActivity extends BaseActivity implements View.OnClickListener {

    private Button btn1;
    private Button btn2;
    private Button btn3;
    private Button btn4;
    private Button btn5;
    private Button btn6;
    private Button btn7;
    private Button btn8;
    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();
        initViews();
    }

    private void initViews() {
        btn1.setOnClickListener(this);//同步get
        btn2.setOnClickListener(this);//异步get
        btn3.setOnClickListener(this);//同步post
        btn4.setOnClickListener(this);//异步post
        //---btn5+btn6+btn7+btn8 使用了EventBus3.0来传递数据，并对OkHttp进行了封装
        btn5.setOnClickListener(this);//同步get
        btn6.setOnClickListener(this);//异步get
        btn7.setOnClickListener(this);//同步post
        btn8.setOnClickListener(this);//同步post
    }

    private void findViews() {
        btn1 = (Button) findViewById(R.id.btn1);
        btn2 = (Button) findViewById(R.id.btn2);
        btn3 = (Button) findViewById(R.id.btn3);
        btn4 = (Button) findViewById(R.id.btn4);
        btn5 = (Button) findViewById(R.id.btn5);
        btn6 = (Button) findViewById(R.id.btn6);
        btn7 = (Button) findViewById(R.id.btn7);
        btn8 = (Button) findViewById(R.id.btn8);
        tv = (TextView) findViewById(R.id.tv_content);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn1:
                syncGet();
                break;
            case R.id.btn2:
                AsyncGet();
                break;
            case R.id.btn3:
                syncPost();
                break;
            case R.id.btn4:
                AsyncPost();
                break;
            case R.id.btn5:
                showProgressDialog();
                UserRequest.getInstance().syncGet("cui", "123456");
                break;
            case R.id.btn6:
                showProgressDialog();
                UserRequest.getInstance().AsyncGet("cui", "123456");
                break;
            case R.id.btn7:
                showProgressDialog();
                UserRequest.getInstance().syncPost("cui", "123456");
                break;
            case R.id.btn8:
                showProgressDialog();
                UserRequest.getInstance().AsyncPost("cui", "123456");
                break;
        }
    }


    @Override
    public void httpSuccessEvent(HttpSuccessEvent event) {
        super.httpSuccessEvent(event);
        if (event.getRequestTag() == RequestTag.GET1 || event.getRequestTag() == RequestTag.GET2 || event.getRequestTag() == RequestTag.POST1 || event.getRequestTag() == RequestTag.POST2) {
            dismissProgressDialog();
            String json = event.getJson();
            tv.setText(json);
            // TODO:  解析数据可以再写一个类JsonParser,将解析结果用EventBus发送过来，EventBus.getDefault().post(event);其中event是AppEvent
        }
    }

    @Override
    public void httpErrorEvent(HttpErrorEvent event) {
        super.httpErrorEvent(event);
        if (event.getRequestTag() == RequestTag.GET1 || event.getRequestTag() == RequestTag.GET2 || event.getRequestTag() == RequestTag.POST1 || event.getRequestTag() == RequestTag.POST2) {
            dismissProgressDialog();
            String json = event.getErrorMessage();
            tv.setText(json);
        }
    }

    @Override
    public void applicationEvent(AppEvent event) {
        super.applicationEvent(event);
        // TODO: 接收httpSuccessEvent(...)中JsonParser成功后发送的结果
    }


    private void syncPost() {
        //OkHttpClient + FormBody + Request + Call
        //1 创建OkHttpClient对象
        //2 创建Request对象 + FormBody
        //3 创建Call对象并执行
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient http = new OkHttpClient();
                FormBody formBody = new FormBody.Builder().add("name", "cqc").add("age", "20").build();
                String url = "http://192.168.1.11:8080/okhttp/json3";
                Request request = new Request.Builder().post(formBody).url(url).build();
                Call call = http.newCall(request);
                try {
                    final Response response = call.execute();
                    final String json = response.body().string();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (response.isSuccessful()) {
                                tv.setText(json);
                            } else {
                                tv.setText("error");
                            }
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    private void AsyncPost() {
        //OkHttpClient + FormBody + Request + Call
        //1 创建OkHttpClient对象
        OkHttpClient http = new OkHttpClient();
        //2 创建Request对象
        FormBody formBody = new FormBody.Builder().add("name", "AndroidCQC").add("age", "20").build();
        String url = "http://192.168.1.11:8080/okhttp/json4";
        Request request = new Request.Builder().post(formBody).url(url).build();
        //3 创建回调对象
        Call call = http.newCall(request);

        //4 执行回调
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(e.getMessage().toString());
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String json = response.body().string();
                            tv.setText(json);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    private void AsyncGet() {
        //1 创建OkHttpClient对象
        OkHttpClient http = new OkHttpClient();
        //2 创建Request对象
        String url = "http://192.168.1.11:8080/okhttp/json2";
        Request request = new Request.Builder().get().url(url).build();
        //3 创建回调对象
        Call call = http.newCall(request);
        //4 执行
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(e.getMessage().toString());
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String json = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tv.setText(json);
                    }
                });
            }
        });
    }

    private void syncGet() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //1 创建OkHttpClient对象
                OkHttpClient http = new OkHttpClient();
                //2 创建请求对象
                String url = "http://192.168.1.11:8080/okhttp/json1";
                Request request = new Request.Builder().get().url(url).build();
                //3 创建回调对象并执行
                try {
                    Response response = http.newCall(request).execute();
                    final String json = response.body().string();
                    if (response.isSuccessful()) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv.setText(json);
                            }
                        });
                    }
                } catch (final IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv.setText("" + e.getMessage().toString());
                        }
                    });
                    e.printStackTrace();
                }
            }
        }).start();
    }


}
